home *** CD-ROM | disk | FTP | other *** search
- Path: qns2.qns.com!not-for-mail
- From: mjarvis@qns2.qns.com (Michael Jarvis)
- Newsgroups: comp.lang.c
- Subject: Re: Why is Gets() so bad?
- Date: 3 Mar 1996 14:29:03 -0600
- Organization: Questar Network Services
- Message-ID: <4hcvef$308@qns2.qns.com>
- References: <4hb1ie$pa7@ixnews2.ix.netcom.com>
- X-Newsreader: TIN [version 1.2 PL2]
-
- Studcat's Big Studdog. (Studcat's Big Studdog. (studwoof@ix.netcom.com)) wrote:
- > Hi.. I'm not a newbie.. I don't even use Gets(), fgets(), or scanf..
- > I use my own getstring function. My question is that everywhere I see
- > that gets() is bad. Why exactly is it so bad? Could someone please
- > explain in more detail than what the FAQ does? Thanks.
-
- Let's say you have the following bit of code:
- ----------------------------------------------------------------------
- #include <stdio.h>
- #include <errno.h>
-
- int main( int argc, char *argv[] )
- {
- char buf[20];
-
- puts( "Please enter some text and press ENTER." );
- puts( " 11111111112" );
- puts( "12345678901234567890" );
-
- if ( gets( buf ) == NULL )
- perror( "Error reading in gets()");
-
- printf( "The buf=\"%s\"\n", buf );
-
- return 0;
- }
- ----------------------------------------------------------------------
-
- The function gets() will blindly read in whatever you type on stdin.
- If you type in more data than it's able to handle (ie more than 20
- bytes in this case) then you've written beyond the boundaries of buf
- and Bad Things will happen.
-
- A better solution would be:
- ----------------------------------------------------------------------
- #include <stdio.h>
- #include <errno.h>
-
- int main( int argc, char *argv[] )
- {
- char buf[20];
-
- puts( "Please enter some text and press ENTER." );
- puts( " 11111111112" );
- puts( "12345678901234567890" );
-
- if ( fgets( buf, sizeof(buf)-1, stdin ) == NULL )
- perror( "Error reading in gets()");
-
- printf( "The buf=\"%s\"\n", buf );
-
- return 0;
- }
- ----------------------------------------------------------------------
-
- By using fgets you can tell it the maximum amount of data to read. You
- could type megs and megs of data but it would only read 19 bytes (leaving
- room for the '\0' at the end).
-
- Using gets() is just asking for trouble, in my opinion.
-
- -michael
- --
- Michael Jarvis | Finger for PGP Public key | QNSnet Technical Support
- mjarvis@qns.com | http://www.qns.com/~mjarvis | Questar Network Services
- GC3.1: GCS d s+++: a26 C++++ USLV++++$ P++++ L++ E--- W++ N++ !o K+ W-- !O
- M- !V PS+ PE Y+ PGP+ t+ 5 X R tv b+++ DI+++ D++ G+ e>++ h---(*) r+++ y+++
-